package com.jxs.easysecurity.utils;

import org.apache.commons.codec.binary.Base64;

import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.security.MessageDigest;
import java.util.Arrays;

/**
 * @author jiangxingshang
 * @since 17/6/21
 */
public class CipherKit {

    private Cipher encode;
    private Cipher decode;

    public CipherKit(String secretKeyText) {
        try {
            MessageDigest sha = MessageDigest.getInstance("SHA-1");
            byte[] key = sha.digest(secretKeyText.getBytes());
            key = Arrays.copyOf(key, 16);
            SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");


            encode = Cipher.getInstance("AES");
            encode.init(Cipher.ENCRYPT_MODE, secretKeySpec);
            decode = Cipher.getInstance("AES");
            decode.init(Cipher.DECRYPT_MODE, secretKeySpec);
        } catch(Exception e) {
            throw new RuntimeException(e);
        }
    }

    public String encode(String content) {
        try {
            byte[] data = encode.doFinal(content.getBytes());
            return Base64.encodeBase64URLSafeString(data);
        } catch(Exception e) {
            throw new RuntimeException(e);
        }
    }

    public String decode(String content) {
        try {
            byte[] data = Base64.decodeBase64(content);
            return new String(decode.doFinal(data));
        } catch(Exception e) {
            throw new RuntimeException(e);
        }
    }
}
